import numpy as np
import matplotlib.pyplot as plt
from math import sin, cos, tan

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

# 例4: 计算 lim(x→0) (e^(1-cos x) - 1) / x²
def example_4():
    from math import exp
    
    # 生成趋近于0的x值
    x_values = np.array([0.1, 0.05, 0.01, 0.005, 0.001, 0.0005, 0.0001])
    
    print("\n例4: 计算 lim(x→0) (e^(1-cos x) - 1) / x²")
    print("=" * 50)
    
    # 直接计算原函数值
    original_values = []
    for x in x_values:
        numerator = exp(1 - cos(x)) - 1
        denominator = x**2
        value = numerator / denominator if denominator != 0 else float('nan')
        original_values.append(value)
        print(f"x = {x:.5f}, 原函数值 = {value:.8f}")
    
    # 使用等价无穷小替换计算
    print("\n使用等价无穷小替换:")
    equivalent_values = []
    for x in x_values:
        # 使用替换: e^u - 1 ~ u (当u→0), 1-cos x ~ x²/2
        # 所以 e^(1-cos x) - 1 ~ 1-cos x ~ x²/2
        # 原式 ~ (x²/2) / x² = 1/2
        value = 0.5
        equivalent_values.append(value)
        print(f"x = {x:.5f}, 替换后值 = {value:.8f}")
    
    # 理论极限值
    theoretical_limit = 0.5
    print(f"\n理论极限值 = {theoretical_limit}")
    
    # 可视化比较
    plt.figure(figsize=(10, 6))
    
    # 绘制原函数值
    plt.semilogx(x_values, original_values, 'bo-', linewidth=2, markersize=6, label='原函数值')
    
    # 绘制替换后值
    plt.semilogx(x_values, equivalent_values, 'ro-', linewidth=2, markersize=6, label='替换后值')
    
    # 绘制理论极限值
    plt.axhline(y=theoretical_limit, color='green', linestyle='--', linewidth=2, label='理论极限 (0.5)')
    
    plt.xlabel('x值 (对数尺度)')
    plt.ylabel('函数值')
    plt.title('例4: 等价无穷小替换演示 - (e^(1-cos x) - 1) / x²')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.show()

# 运行示例
example_4()
